<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学习复习表SOP模板</title>
    <script src="https://cdn.tailwindcss.com"></script>
    
    <!-- JS 库将移到 body 底部 -->
    
    <link href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;700&family=Source+Han+Sans+CN:wght@300;400;700&display=swap" rel="stylesheet">
    
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6', // 蓝色
                        danger: '#EF4444', // 红色
                        'light-blue-bg': '#EFF6FF',
                        'dark-blue-text': '#1E40AF',
                        'icon-blue': '#60A5FA',
                        'icon-green': '#34D399',
                        'icon-purple': '#A78BFA',
                        'icon-orange': '#F59E0B',
                    }
                }
            }
        }
    </script>
    <style>
        :root {
            --theme-primary: #3B82F6;
            --theme-secondary: #10B981;
            --highlight-bg: #EFF6FF;
            --highlight-text: #1E40AF;
        }
        body {
            font-family: 'Source Han Sans CN', sans-serif;
            font-weight: 300;
            background-color: #f3f4f6;
            /* 恢复居中 */
            display: flex;
            justify-content: center;
            padding: 32px; /* p-8 */
            min-height: 100vh;
        }
        h1, h2, h3, blockquote {
            font-family: 'Noto Serif SC', serif;
        }

        .tool-container {
            width: 1000px; 
            max-width: 90vw;
            background: #ffffff;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.08);
            margin: 0; /* 移除 auto margin */
            padding: 40px;
            flex-shrink: 0;
            height: fit-content;
        }
        
        /* 导出按钮样式 */
        .export-btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            color: white;
            border: none;
            padding: 12px 28px;
            font-size: 1.0em;
            font-weight: 700;
            border-radius: 8px;
            cursor: pointer;
            transition: opacity 0.3s, transform 0.2s;
            font-family: 'Source Han Sans CN', sans-serif;
            text-decoration: none;
        }
        .btn-pdf {
            background-color: #EF4444; /* 红色 */
        }
        .btn-pdf:hover { opacity: 0.85; transform: translateY(-1px); }
        
        .btn-doc {
            background-color: #3B82F6; /* 蓝色 */
            margin-left: 16px;
        }
        .btn-doc:hover { opacity: 0.85; transform: translateY(-1px); }

        .export-btn.loading {
            background-color: #9ca3af;
            cursor: wait;
        }

        /* 笔记法标题图标 */
        .section-title-icon {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: var(--highlight-bg);
            color: var(--theme-primary);
            flex-shrink: 0;
            margin-right: 12px;
        }

        /* 复习表特定样式 (表格) */
        .editable-table {
            width: 100%; 
            border-collapse: collapse; 
            border: 1px solid #ddd; 
            font-size: 14px;
            margin-top: 16px;
        }
        .editable-table th {
            border: 1px solid #ddd; 
            padding: 12px; 
            background-color: #f4f4f4; 
            text-align: left;
            font-weight: 700;
            font-family: 'Noto Serif SC', serif;
            font-size: 1.1em;
            text-align: center;
        }
        .editable-table td {
            border: 1px solid #ddd; 
            padding: 12px; 
            vertical-align: top;
            cursor: text;
            min-height: 80px;
        }
        .editable-table td[contenteditable="true"]:empty:before {
            content: "点击填写...";
            color: #aaa;
            font-style: italic;
        }

        /* 打印时隐藏的元素 */
        @media print {
            .no-print { display: none; }
        }
        
    </style>
</head>
<body class="bg-gray-100 flex justify-center p-8 min-h-screen">

    <div class="tool-container" id="review-export-area">

        <!-- 页面头部 -->
        <header class="mb-8 no-print"> 
            <h1 class="text-3xl font-bold text-gray-800">学习复习表SOP模板</h1>
            <p class="text-lg text-gray-500 mt-2">艾宾浩斯遗忘曲线复习工具</p>
        </header>

        <!-- 方法简介 -->
        <div class="bg-light-blue-bg border-l-4 border-primary p-6 rounded-lg my-6 no-print">
            <h3 class="font-bold text-lg text-dark-blue-text">方法简介</h3>
            <p class="text-gray-700 mt-2">
                根据艾宾浩斯遗忘曲线，学习后的重复复习是巩固记忆的关键。使用此表来规划您的复习周期，确保知识真正内化。
            </p>
        </div>

        <!-- 导出按钮区域 (恢复) -->
        <div class="my-8 text-left no-print">
            <button class="export-btn btn-pdf" id="pdf-button">
                <span>导出为PDF</span>
            </button>
            <a href="#" class="export-btn btn-doc" id="doc-button">
                <span>导出为文档</span>
            </a>
        </div>

        <!-- 在线填写区域 -->
        <section id="review-content" class="border-t border-gray-200 pt-8">
            
            <!-- 大标题 -->
            <div class="flex items-center mb-6">
                <div class="section-title-icon" id="title-icon-placeholder">
                     <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 2v4"></path><path d="M16 2v4"></path><rect width="18" height="18" x="3" y="4" rx="2"></rect><path d="M3 10h18"></path><path d="m9 16 2 2 4-4"></path></svg>
                </div>
                <h2 id="note-title" class="text-2xl font-bold text-gray-800" contenteditable="true">[请填写学习主题]</h2>
            </div>
            
            <!-- 复习表 -->
            <table class="editable-table">
                <thead>
                    <tr>
                        <th style="width: 25%; background-color: var(--theme-primary); color: white;">Target/Date (目标/日期)</th>
                        <th style="width: 25%; background-color: var(--theme-secondary); color: white;">First time (第一次复习)</th>
                        <th style="width: 25%; background-color: #F59E0B; color: white;">Second time (第二次复习)</th>
                        <th style="width: 25%; background-color: #A78BFA; color: white;">Third time (第三次复习)</th>
                    </tr>
                </thead>
                <tbody id="review-table-body">
                    <tr>
                        <td contenteditable="true" style="background-color: var(--highlight-bg);">例如：2025-11-03 学习xx理论</td>
                        <td contenteditable="true" style="background-color: var(--highlight-bg);">例如：2025-11-04 (1天后)</td>
                        <td contenteditable="true">例如：2025-11-10 (1周后)</td>
                        <td contenteditable="true">例如：2025-12-03 (1月后)</td>
                    </tr>
                    <tr>
                        <td contenteditable="true"></td>
                        <td contenteditable="true"></td>
                        <td contenteditable="true"></td>
                        <td contenteditable="true"></td>
                    </tr>
                    <tr>
                        <td contenteditable="true"></td>
                        <td contenteditable="true"></td>
                        <td contenteditable="true"></td>
                        <td contenteditable="true"></td>
                    </tr>
                </tbody>
            </table>

            <!-- 新增：添加行按钮 -->
            <div class="text-left mt-4 no-print">
                <button id="add-row-btn" class="text-sm text-primary font-semibold flex items-center">
                    <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="mr-1"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="16"></line><line x1="8" y1="12" x2="16" y2="12"></line></svg>
                    添加一行
                </button>
            </div>
        </section>
        
    </div> <!-- .tool-container end -->

    <!-- 恢复所有功能性JS库 -->
    <script src="https://unpkg.com/lucide@latest"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

    <script>
        // 将所有初始化代码包裹在一个大的 try...catch 和 window.onload 中
        window.onload = function() {
            try {
                // --- 1. 图标加载 ---
                try {
                    if (typeof lucide !== 'undefined') {
                        // 按钮图标
                        document.getElementById('pdf-button').innerHTML = '<i data-lucide="file-text" class="inline-block w-5 h-5 mr-2"></i> 导出为PDF';
                        document.getElementById('doc-button').innerHTML = '<i data-lucide="file-text" class="inline-block w-5 h-5 mr-2"></i> 导出为文档';
                        
                        // 内容图标 (SVG 已硬编码)
                        
                        lucide.createIcons();
                    } else {
                        console.warn("Lucide library not loaded.");
                    }
                } catch (e) {
                    console.error("Icon loading failed:", e);
                }

                // --- 2. 添加行功能 ---
                try {
                    const addRowBtn = document.getElementById('add-row-btn');
                    if (addRowBtn) {
                        addRowBtn.addEventListener('click', () => {
                            const tableBody = document.getElementById('review-table-body');
                            const newRow = document.createElement('tr');
                            newRow.innerHTML = `
                                <td contenteditable="true"></td>
                                <td contenteditable="true"></td>
                                <td contenteditable="true"></td>
                                <td contenteditable="true"></td>
                            `;
                            tableBody.appendChild(newRow);
                        });
                    }
                } catch (e) {
                     console.error("Add row button init failed:", e);
                }


                // --- 3. PDF 生成功能 (使用横向布局) ---
                try {
                    const pdfButton = document.getElementById('pdf-button');
                    if (pdfButton) {
                        pdfButton.addEventListener('click', async function() {
                            if (typeof html2canvas === 'undefined' || typeof window.jspdf === 'undefined') {
                                alert("PDF生成库加载失败，请检查网络连接并刷新页面。");
                                return;
                            }
                            const { jsPDF } = window.jspdf;
                            const button = this;
                            const exportArea = document.getElementById('review-export-area'); 
                            const title = document.getElementById('note-title').textContent.trim() || '学习复习表';

                            button.classList.add('loading');
                            button.innerHTML = '<span><i data-lucide="loader-2" class="inline-block w-5 h-5 mr-2 animate-spin"></i> 正在生成PDF...</span>';
                            if (typeof lucide !== 'undefined') lucide.createIcons();
                            
                            window.scrollTo(0, 0);

                            try {
                                const canvas = await html2canvas(exportArea, {
                                    scale: 2,
                                    useCORS: true,
                                    onclone: (doc) => {
                                        doc.querySelectorAll('.no-print').forEach(el => el.style.display = 'none');
                                        doc.querySelectorAll('.editable-table td:empty:before').forEach(el => el.style.display = 'none');
                                    }
                                });
                                
                                const imgData = canvas.toDataURL('image/png');
                                
                                // 修复：使用横向 (Landscape)
                                const pdfWidth = 841.89; // A4 横向宽度 (pt)
                                const pdfHeight = (canvas.height * pdfWidth) / canvas.width;
                                
                                const pdf = new jsPDF({
                                    orientation: 'landscape', // 横向
                                    unit: 'pt',
                                    format: [pdfWidth, pdfHeight]
                                });

                                pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
                                pdf.save(`${title}.pdf`);

                            } catch (err) {
                                console.error('生成PDF失败: ', err);
                                alert("生成PDF失败，请重试。");
                            } finally {
                                button.classList.remove('loading');
                                button.innerHTML = '<span><i data-lucide="file-text" class="inline-block w-5 h-5 mr-2"></i> 导出为PDF</span>';
                                if (typeof lucide !== 'undefined') lucide.createIcons();
                            }
                        });
                    }
                } catch (e) {
                    console.error("PDF button init failed:", e);
                }

                // --- 4. 导出Word文档功能 (修复了“无响应”bug) ---
                try {
                    const docButton = document.getElementById('doc-button');
                    if (docButton) {
                        let isDocFileReady = false;
                        docButton.addEventListener('click', function(e) {
                            if (isDocFileReady) {
                                // 第二次点击
                                isDocFileReady = false;
                                setTimeout(() => {
                                    this.classList.remove('loading');
                                    this.innerHTML = '<span><i data-lucide="file-text" class="inline-block w-5 h-5 mr-2"></i> 导出为文档</span>';
                                    if (typeof lucide !== 'undefined') lucide.createIcons();
                                }, 1000);
                                // 移除了 return;
                            } else {
                                // 第一次点击
                                e.preventDefault(); 
                                this.classList.add('loading');
                                this.innerHTML = '<span><i data-lucide="loader-2" class="inline-block w-5 h-5 mr-2 animate-spin"></i> 正在生成文档...</span>';
                                if (typeof lucide !== 'undefined') lucide.createIcons();

                                setTimeout(() => {
                                    try {
                                        const title = document.getElementById('note-title').innerHTML;
                                        const table = document.querySelector('.editable-table').cloneNode(true);
                                        table.querySelectorAll('[contenteditable="true"]').forEach(cell => cell.removeAttribute('contenteditable'));
                                        const tableHTML = table.outerHTML;

                                        const h1Style = "font-family: 'Noto Serif SC', serif; color: #333; text-align: left; font-size: 1.8em; font-weight: 700; margin-bottom: 24px; border-bottom: 2px solid #f0f0f0; padding-bottom: 10px;";
                                        
                                        const wordHtmlContent = `
                                            <div style="font-family: 'Source Han Sans CN', 'Microsoft YaHei', sans-serif; margin: 30px; max-width: 900px;">
                                                <h1 style="${h1Style}">${title}</h1>
                                                ${tableHTML
                                                    .replace(/style="background-color: var\(--highlight-bg\);"/g, 'style="background-color: #EFF6FF;"')
                                                    .replace(/style="width: 25%; background-color: var\(--theme-primary\); color: white;"/g, 'style="width: 25%; background-color: #3B82F6; color: white;"')
                                                    .replace(/style="width: 25%; background-color: var\(--theme-secondary\); color: white;"/g, 'style="width: 25%; background-color: #10B981; color: white;"')
                                                    .replace(/style="width: 25%; background-color: #F59E0B; color: white;"/g, 'style="width: 25%; background-color: #F59E0B; color: white;"')
                                                    .replace(/style="width: 25%; background-color: #A78BFA; color: white;"/g, 'style="width: 25%; background-color: #A78BFA; color: white;"')
                                                }
                                            </div>
                                        `;
                                        
                                        const fullHtml = `<!DOCTYPE html><html lang="zh-CN"><head><meta charset="UTF-8"><title>${title.replace(/<[^>]*>?/gm, '')}</title></head><body>${wordHtmlContent}</body></html>`;
                                        const finalHtml = fullHtml
                                            .replace(/<td contenteditable="true"><\/td>/g, '<td>&nbsp;</td>')
                                            .replace(/<td><\/td>/g, '<td>&nbsp;</td>');

                                        
                                        const dataUri = 'data:application/vnd.ms-word;base64,' + btoa(unescape(encodeURIComponent(finalHtml)));
                                        
                                        this.href = dataUri;
                                        this.download = `${title.replace(/<[^>]*>?/gm, '')}.doc`;
                                        
                                        this.classList.remove('loading');
                                        this.innerHTML = '<span><i data-lucide="check-circle" class="inline-block w-5 h-5 mr-2"></i> 已就绪, 请再次点击下载</span>';
                                        if (typeof lucide !== 'undefined') lucide.createIcons();
                                        
                                        isDocFileReady = true;

                                    } catch (err) {
                                        console.error("生成Word失败:", err);
                                        alert("生成文档失败，请重试。");
                                        this.classList.remove('loading');
                                        this.innerHTML = '<span><i data-lucide="file-text" class="inline-block w-5 h-5 mr-2"></i> 导出为文档</span>';
                                        if (typeof lucide !== 'undefined') lucide.createIcons();
                                    }
                                }, 100);
                            }
                        });
                    }
                } catch (e) {
                     console.error("Doc button init failed:", e);
                }
                
            } catch (e) {
                console.error("A fatal error occurred during initialization:", e);
            }
        }
    </script>
</body>
</html>

